package com.st.demo;
import android.animation.ObjectAnimator;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.RotateAnimation;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class  MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener, AMap.OnMarkerClickListener, AMap.OnMarkerDragListener, AMap.OnMapClickListener, AMap.InfoWindowAdapter {
    private MapView mMapView;//声明一个地图视图对象
    private AMap aMap;//声明一个地图图层
    private OnLocationChangedListener mListener;//声明位置监听
    private AMapLocationClient mlocationClient;//声明定位客户端
    private AMapLocationClientOption mLocationOption;//声明定位参数配置选项
    private boolean isFirstLoc = true;//判断是否第一次定位
    private LatLng currentLatLng;//当前定位

    private UiSettings mUiSettings;//定义一个UiSettings对象
    private View markerView;
    private Marker current;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LayoutInflater inflater = getLayoutInflater();
        //初始化地图定位
        initMap(savedInstanceState);

    }
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };
    /**
     * 初始化地图
     * @param savedInstanceState
     */
    private void initMap(Bundle savedInstanceState) {
        //隐私合规接口
        MapsInitializer.updatePrivacyShow(this, true, true);
        MapsInitializer.updatePrivacyAgree(this, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
        AMapLocationClient.updatePrivacyShow(this, true, true);
        //获取地图视图对象
        mMapView = findViewById(R.id.map);
        //创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        //设置了定位的监听
        aMap.setLocationSource(this);
        //设置marker点击事件
        aMap.setOnMarkerClickListener(this);
        //设置marker拖拽监听事件
        aMap.setOnMarkerDragListener(this);
        //地图点击监听事件
        aMap.setOnMapClickListener(this);
        //设置InfoWindow适配器
        aMap.setInfoWindowAdapter(this);
        //绑定信息窗点击事件
        aMap.setOnInfoWindowClickListener(listener);

        //初始化定位蓝点样式类
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);//设置定位模式
        myLocationStyle.interval(2000); //只在连续定位模式下生效
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点
        // 将定位蓝点移动到屏幕中心
        myLocationStyle.anchor(0.5f, 0.5f).myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的边框颜色:无色
        myLocationStyle.radiusFillColor(Color.argb(0, 255, 255, 255)); // 设置精度圆圈背景色：透明无色
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 是否启动显示定位蓝点,默认是false。

        //控件交互
        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(true);//缩放按钮
        mUiSettings.setZoomPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
        mUiSettings.setCompassEnabled(true);//指南针
        mUiSettings.setMyLocationButtonEnabled(true);//定位按钮
        mUiSettings.setScaleControlsEnabled(true);//比例尺控件
        mUiSettings.setZoomGesturesEnabled(true);
        //marker标记物
        LatLng latLng = new LatLng(31.042119,121.410428);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("测试1").snippet("我是默认marker").alpha(1.0f));

        //绘制自定义带文字的marker
        BitmapDescriptor withDataIcon = drawIcon(R.drawable.icon_marker_orange, "李", Color.WHITE);
        LatLng latLng2 = new LatLng(31.041991,121.409628);
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng2);
        markerOption.title("测试").snippet("我是携带文字信息的marker");
        markerOption.draggable(true);//设置Marker可拖动
        markerOption.icon(withDataIcon);
        markerOption.setFlat(false);//设置marker平贴地图效果
        aMap.addMarker(markerOption);

        List<LatLng> positon = new ArrayList<>();
        positon.add(new LatLng(31.041742,121.411517));
        positon.add(new LatLng(31.041370,121.411699));
        positon.add(new LatLng(31.041563,121.412198));
        //绘制自定义marker
        MarkerOptions options = new MarkerOptions();
        for (int i = 0; i < positon.size(); i++) {
            options.position(positon.get(i));
            options.title("测试"+i);
            options.snippet("内容"+i);
            aMap.addMarker(options);
        }
    }

    /**
     * 绘制带文字的marker
     * @param markerStyle 图片资源
     * @param text        文字
     * @param textColor   文字颜色
     * @return
     */
    private BitmapDescriptor drawIcon(int markerStyle, String text, int textColor) {
        Bitmap bitmap = null;
        BitmapDescriptor icon = null;
        try {
            bitmap = BitmapFactory.decodeResource(getResources(), markerStyle);//图片转bitmap位图
            int markerStyleWidth = bitmap.getWidth();//获取bitmap位图的宽
            int markerStyleHeight = bitmap.getHeight();//获取bitmap位图的高
            Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);//复制Bitmap对象
            Canvas canvas = new Canvas(mutableBitmap); //创建Canvas对象
            Paint paint = new Paint();//创建Paint对象，用于定义绘制文本的样式
            paint.setColor(textColor);//设置文字颜色
            paint.setTextSize(getResources().getDimensionPixelSize(R.dimen.text_size));//设置文字大小
            //获取文本边界
            Rect textBounds = new Rect();
            paint.getTextBounds(text, 0, text.length(), textBounds);
            int textWidth = textBounds.width();//文本宽度
            int textHeight = textBounds.height();//文本高度
            //计算文字在图片上的坐标，使其在图片居中位置
            float x = (markerStyleWidth - textWidth) / 2.0f;//x表示绘制文本起始点的横坐标,从左开始
            float y = (markerStyleHeight + textHeight) / 2.0f - 20;//x表示绘制文本起始点的纵坐标,从顶部开始
            canvas.drawText(text, x, y, paint); //使用Canvas绘制文本
            icon = BitmapDescriptorFactory.fromBitmap(mutableBitmap);// 最后将Bitmap 转换为 BitmapDescriptor
            return icon;
        } catch (Resources.NotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (bitmap != null) {
                bitmap.recycle();
            }
            if (icon != null) {
                icon.recycle();
            }
        }


    }

    /**
     * 激活定位
     */
    @Override
    public void activate(LocationSource.OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位
            try {
                mLocationOption = new AMapLocationClientOption();//初始化定位参数
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//设置为高精度定位模式
                mlocationClient = new AMapLocationClient(this);//声明定位客户端
                mlocationClient.setLocationListener(this);//设置定位回调监听
                mlocationClient.setLocationOption(mLocationOption);//设置定位参数
                mlocationClient.startLocation();//启动定位
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 监听定位回调
     * @param aMapLocation
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
                // 是否第一次定位
                if (isFirstLoc) {
                    aMap.moveCamera(CameraUpdateFactory.zoomTo(16));//设置缩放级别
                    currentLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude()); //获取当前定位
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(currentLatLng));//移动到定位点
                    //点击定位按钮 能够将地图的中心移动到定位点
                    mListener.onLocationChanged(aMapLocation);
                    isFirstLoc = false;
                }

            } else {
                //显示错误信息
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    }

    /**
     * 生命周期-onDestroy
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy(); //销毁地图
    }
    /**
     * 生命周期-onResume
     */
    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume(); //重新绘制加载地图
    }
    /**
     * 生命周期-onPause
     */
    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();//暂停地图的绘制
    }
    /**
     * 生命周期-onSaveInstanceState
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);//保存地图当前的状态
    }
    private boolean isMarkerClicked = false;
    /**
     * marker 对象被点击时回调的接口
     * 返回 true 则表示接口已响应事件，否则返回false
     * @param marker
     * @return
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        current = marker;
        isMarkerClicked = true;
        marker.showInfoWindow();
        return false;
    }

    /**
     * 当marker开始被拖动时回调此方法, 这个marker的位置可以通过getPosition()方法返回。
     * @param marker
     */
    @Override
    public void onMarkerDragStart(Marker marker) {
        Log.d("MainActivity", "Start: "+marker.getPosition());
    }
    /**
     *  在marker拖动过程中回调此方法, 这个marker的位置可以通过getPosition()方法返回。
     * @param marker
     */
    @Override
    public void onMarkerDrag(Marker marker) {
        Log.d("MainActivity", "Drag: "+marker.getPosition());
    }

    /**
     * 在marker拖动完成后回调此方法, 这个marker的位置可以通过getPosition()方法返回。
     * @param marker
     */
    @Override
    public void onMarkerDragEnd(Marker marker) {
        Log.d("MainActivity", "End: "+marker.getPosition());
    }

    /**
     * map地图点击监听事件
     * @param latLng
     */
    @Override
    public void onMapClick(LatLng latLng) {
        if (!isMarkerClicked) {
            if (current != null && current.isInfoWindowShown()) {
                current.hideInfoWindow();//
            }
        }
        isMarkerClicked = false; // 重置标记状态
    }

    View infoWindow = null;
    @Override
    public View getInfoWindow(Marker marker) {
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(this).inflate(R.layout.custom_info_window, null);
        }
        render(marker, infoWindow);
        return infoWindow;
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        //如果想修改自定义Infow中内容，请通过view找到它并修改
        String title = marker.getTitle();
        TextView titleUi = view.findViewById(R.id.title);
        titleUi.setText(title);
        String snippet = marker.getSnippet();
        TextView snippetUi = view.findViewById(R.id.snippet);
        snippetUi.setText(snippet);
    }
}